package pl.enigmatic.parser.metadata;

import org.apache.log4j.Logger;
import org.apache.log4j.xml.DOMConfigurator;

import pl.enigmatic.parser.xml.Parser;
import pl.enigmatic.parser.xml.ParsingInfo;
import pl.enigmatic.parser.xml.ParsingMetadata;
import pl.enigmatic.parser.xml.PropertySetter;
import pl.enigmatic.parser.xml.StaticParsingInfo;


public class NameExtension extends MetadataParserExtension {

	static {
		DOMConfigurator.configure("log4j.xml");
	}

	/** logging utility object */
	private static Logger logger = Logger.getLogger(NameExtension.class);

	public static NameExtension instance = new NameExtension();

	public NameExtension() {
		super(Metadata.NAME);
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public boolean parseMetadata(final Object target, final ParsingInfo<?> info, final String name) {
		final StaticParsingInfo staticInfo = info.getStaticInfo();
		if (!staticInfo.addNamedObject(name, target)) {
			logger.error(String.format("Duplicate id for name %1$s.", name), new Exception("Ambiguous name."));
			return false;
		} else if (info.getRootParser().hasNamedProperties()) {
			info.getRootParser().addNamedProperty(info.getRoot().getTarget(), name, target);
		}
		if (staticInfo.getMetadataBoolean(ParsingMetadata.META_NAME_IS_NAME_PROPERTY)) {
			Parser parser = info.getParser();
			final PropertySetter setter = parser.accessor(parser.getPropertyName(Metadata.NAME.toString()));
			if (setter != null) {
				parser = setter.getParser();
				if (parser != null && parser.hasConverter()) {
					setter.access(target, parser.convert(name, info), info);
					// FIXME - to może powodować problemy bardzo rzadkie ale głębokie :-)
				}
			}
		}
		return true;
	}
}
